using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Security.Cryptography;
using System.Xml;
using CodePlex.Resourceful;

namespace CodePlex.SpaceBlock
{
    public static class SpaceBlockUtils
    {

        public static string Decrypt(string cipherText, string password)
        {
            string[] hex = cipherText.Split('-');
            byte[] cipher = new byte[hex.Length];
            for (int i = 0; i < hex.Length; i++)
            {
                cipher[i] = Byte.Parse(hex[i], NumberStyles.HexNumber);
            }            
            byte[] keyBytes = ProtectedData.Unprotect(cipher, Encoding.Unicode.GetBytes(password), DataProtectionScope.CurrentUser);
            return Encoding.Unicode.GetString(keyBytes);

        }
        public static string Encrypt(string plainText, string password)
        {
            byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
            byte[] entropyBytes = Encoding.Unicode.GetBytes(password);
            byte[] encryptedBytes = ProtectedData.Protect(plainBytes, entropyBytes, DataProtectionScope.CurrentUser);

            return BitConverter.ToString(encryptedBytes);
        }
       
        public static IEnumerable<string> GetContentTypeCategories()
        {
            List<string> rt = new List<string>();

            foreach (string contentType in SpaceBlockUtils.GetContentTypes())
            {
                string category = contentType.Split('/')[0];
                if (!rt.Contains(category))
                {
                    rt.Add(category);
                }
            }

            rt.Add("application/x");
            rt.Sort();
            return rt.ToArray();
        }

        public static string[] GetContentTypes()
        {
            return SpaceBlockUtils.GetContentTypes(null);
        }

        public static string[] GetContentTypes(string category)
        {
            IEnumerable<string> values = MimeMap.List();
            List<string> rt = new List<string>(values);
         
            rt = rt.FindAll(delegate(string item)
            {
                if (category == null)
                {
                    return true;
                }
                if (category.Equals("application",StringComparison.InvariantCultureIgnoreCase))
                {
                    return MonoCompat124.StartsWith(item, category, StringComparison.InvariantCultureIgnoreCase)
                    && !MonoCompat124.StartsWith(item, "application/x-", StringComparison.InvariantCultureIgnoreCase);
                }

                return MonoCompat124.StartsWith(item, category, StringComparison.InvariantCultureIgnoreCase);
            });
            rt.Sort();
            return rt.ToArray();
        }

    }
}
